package com.sdx.console.evaluation.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.POIUtils;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.evaluation.entity.*;
import com.sdx.console.evaluation.service.*;
import com.sdx.console.evaluation.web.query.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 测评任务 接口
 */
@RequestMapping("/evaluation/cpTaskSetup")
@Controller
public class CpTaskSetupController extends AuthorizedBaesController {
    private static final Logger log = LoggerFactory.getLogger(CpTaskSetupController.class);
    private static final String MODEL = "/evaluation/cpTaskSetup";

    @Resource
    private SQLManager sqlManager;

    @Resource
    private CpTaskSetupService cpTaskSetupService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private CpTemplateService cpTemplateService;

    @Resource
    private CpTaskDataService cpTaskDataService;

    @Resource
    private  CpTemplateItemService cpTemplateItemService;

    @Autowired
    FileService fileService;

    /**
     * 初始化页面需要的列表数据，
     */
    private void setPageParam(ModelAndView view, HttpServletRequest request) {
        CpTemplate condtion = new CpTemplate();
        condtion.setIsOpen("1");
        PageQuery page = condtion.getPageQuery();
        cpTemplateService.queryByCondition(page);
        List<CpTemplate> tempList = page.getList();
        view.addObject("tempList", tempList);

    }

    /* 页面 */

    @GetMapping("/ruleindex.do")
    @ResponseBody
    public ModelAndView ruleindex(HttpServletRequest request,Integer taskId) {
        ModelAndView view = new ModelAndView(MODEL + "/rule.html");
        CpTaskSetup cpTaskSetup = cpTaskSetupService.queryById(taskId);
        String person = "参加评测总人数:"+cpTaskSetup.getTotalNum()+"&nbsp;&nbsp;&nbsp;&nbsp;测评人数:"+cpTaskSetup.getAssessNum()+"&nbsp;&nbsp;&nbsp;&nbsp;被测评人数:"+cpTaskSetup.getBeassessNum();
        List<CpTaskData> taskData = cpTaskSetupService.selectGroup(taskId);
        StringBuffer sb = new StringBuffer();
        for (CpTaskData taskDatum : taskData) {
            sb.append(taskDatum.getURole()).append(":"+taskDatum.getUWeight()).append("&nbsp;&nbsp;&nbsp;&nbsp;");
        }
        view.addObject("person",person);
        view.addObject("rule",sb.toString());
        view.addObject("taskId",taskId);
        return view;
    }

    @GetMapping("/index.do")
    @Function("evaluation.cpTaskSetup.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL + "/index.html");
        setPageParam(view, request);
        return view;
    }


    @GetMapping("/edit.do")
    @Function("evaluation.cpTaskSetup.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request, Integer taskId) {
        ModelAndView view = new ModelAndView(MODEL + "/add.html");
        CpTaskSetup cpTaskSetup = cpTaskSetupService.queryById(taskId);
        view.addObject("cpTaskSetup", cpTaskSetup);
        setPageParam(view, request);
        try {
            view.addObject("cpTaskSetupJson", JacksonUtils.toJsonString(cpTaskSetup, JacksonUtils.DF1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }

    @GetMapping("/add.do")
    @Function("evaluation.cpTaskSetup.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL + "/add.html");
        setPageParam(view, request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("evaluation.cpTaskSetup.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CpTaskSetup condtion) {
        PageQuery page = condtion.getPageQuery();
        cpTaskSetupService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew, CpTaskSetup cpTaskSetup, HttpServletRequest request, MultipartFile assessFileFile) {

        if(StringUtils.isNotEmpty(cpTaskSetup.getTaskId()+"")){
            //删除taskId
            cpTaskDataService.delDataByTaskId(cpTaskSetup.getTaskId());
        }

        JsonResult result = JsonResult.success();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/task/" + dir + "/";
        String bucketName = "sdxcomm";
        List<List<String>> lists = new ArrayList<>();
        if (!FileUtils.isEmptyFile(assessFileFile)) {
            String path = "";
            MultipartFile assessFile =  assessFileFile;
            try {
                String assessFileFileNamePair = FileUtils.upload(subPath, assessFileFile);
                String assessFileStoreFile = assessFileFileNamePair.split("::")[0];
                assessFileStoreFile = subPath + assessFileStoreFile;
                path = FileUtils.getRoot() + assessFileStoreFile;
            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
            log.info(assessFile.getOriginalFilename());
            try {
                if (path.endsWith(".xls")) {
                    lists = POIUtils.readXls(path);
                } else if (path.endsWith(".xlsx")) {
                    lists = POIUtils.readXlsx(path);
                } else {
                    return JsonResult.failMessage("文件格式不正确");
                }
                cpTaskSetup.setAssessFile(path);
            } catch (Exception e) {

            }
        }
        CoreUser user = getLoginUser(request);
        List<CpTaskData> taskDataList = new ArrayList<>();
        int assessCont = 0;
        int beassessCount = 0;
        for (List<String> list : lists) {
            CpTaskData cpTaskData = new CpTaskData();
            cpTaskData.setMisNo(list.get(1));
            cpTaskData.setUName(list.get(2));
            cpTaskData.setGroupName(list.get(3));
            String isAssess ="0";
            if("是".equals(list.get(5))){
                assessCont++;
                isAssess = "1";
            }
            cpTaskData.setIsAssess(isAssess);
            String isBeassess = "0";
            if("是".equals(list.get(4))){
                isBeassess ="1";
                beassessCount++;
            }
            cpTaskData.setIsBeassess(isBeassess);
            cpTaskData.setURole(list.get(6));
            cpTaskData.setUWeight( Double.valueOf(list.get(7)).intValue());
            cpTaskSetup.setCreatedBy(user.getId().intValue());
            cpTaskSetup.setCreatedName(user.getName());
            cpTaskSetup.setCreatedTime(new Date());
            taskDataList.add(cpTaskData);
        }

        //校验数据
        if(taskDataList.size()!=cpTaskSetup.getTotalNum()){
            return JsonResult.failMessage("校验失败,请检查文件数据是否正确!");
        }

        if (isNew) {
            cpTaskSetup.setCreatedBy(user.getId().intValue());
            cpTaskSetup.setCreatedName(user.getName());
            cpTaskSetup.setCreatedTime(new Date());
            sqlManager.insert(CpTaskSetup.class,cpTaskSetup,true);
            Integer taskId = cpTaskSetup.getTaskId();
            for (CpTaskData cpTaskData : taskDataList) {
                cpTaskData.setTaskId(taskId);
                cpTaskDataService.save(cpTaskData);
            }
        } else {
            cpTaskDataService.delDataByTaskId(cpTaskSetup.getTaskId());
            for (CpTaskData cpTaskData : taskDataList) {
                cpTaskData.setTaskId(cpTaskSetup.getTaskId());
                cpTaskDataService.save(cpTaskData);
            }
            cpTaskSetup.setUpdatedBy(user.getId().intValue());
            cpTaskSetup.setUpdatedName(user.getName());
            cpTaskSetup.setUpdatedTime(new Date());
            cpTaskSetupService.updateTemplate(cpTaskSetup);
        }
        return JsonResult.success(cpTaskSetup.getTaskId());
    }

    @PostMapping("/add.json")
    @Function("evaluation.cpTaskSetup.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class) CpTaskSetup cpTaskSetup, HttpServletRequest request
            , @RequestParam("assessFileFile") MultipartFile assessFileFile
    ) {

        return save(true, cpTaskSetup, request
                , assessFileFile
        );
    }

    @PostMapping("/update.json")
    @Function("evaluation.cpTaskSetup.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) CpTaskSetup cpTaskSetup, HttpServletRequest request
            , @RequestParam("assessFileFile") MultipartFile assessFileFile
    ) {
        return save(false, cpTaskSetup, request
                , assessFileFile
        );
    }


    @GetMapping("/view.json")
    @Function("evaluation.cpTaskSetup.query")
    @ResponseBody
    public JsonResult<CpTaskSetup> queryInfo(Integer taskId) {
        CpTaskSetup cpTaskSetup = cpTaskSetupService.queryById(taskId);
        return JsonResult.success(cpTaskSetup);
    }

    @PostMapping("/delete.json")
    @Function("evaluation.cpTaskSetup.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        List<String> idList = Utils.strToList(ids, ",");
        cpTaskSetupService.batchDelCpTaskSetup(idList);
        return JsonResult.success();
    }


    @PostMapping("/excel/process.json")
    @Function("evaluation.cpTaskSetup.process")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,Integer taskId) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此cpTaskSetupService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/cp/process.xls";
        //本次导出需要的数据
        List<CpTaskData> list = cpTaskDataService.selectExportData(taskId);
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("中层干部测评任务进度表_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }

    @RequestMapping("/excel/result.json")
    @Function("evaluation.cpTaskSetup.result")
    @ResponseBody
    public JsonResult<String> exportresult(HttpServletResponse response,Integer taskId) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此cpTaskSetupService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/cp/result.xls";
        //本次导出需要的数据
        List<CpTaskSetup> list =cpTaskSetupService.selectExportResult(taskId);
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("中层干部测评结果表_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }

    @GetMapping("/check.do")
    @Function("evaluation.cpTaskSetup.check")
    @ResponseBody
    public ModelAndView check(HttpServletRequest request, Integer taskId) {
        ModelAndView view = new ModelAndView(MODEL + "/check.html");
        CpTaskSetup cpTaskSetup = cpTaskSetupService.queryById(taskId);
        view.addObject("cpTaskSetup", cpTaskSetup);
        setPageParam(view, request);
        try {
            List<CpTemplateItem> cpTemplateItemList = cpTemplateItemService.selectCpTemplateItem(cpTaskSetup.getTplId());
            List<CpTaskData> cpTaskData = cpTaskDataService.selectCpTaskData(taskId);

            view.addObject("cpTemplateItemList",JacksonUtils.toJsonString(cpTemplateItemList,JacksonUtils.DF1));
            view.addObject("cpTaskSetupJson", JacksonUtils.toJsonString(cpTaskSetup, JacksonUtils.DF1));

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }

    @GetMapping("/checkData.do")
    @Function("evaluation.cpTaskSetup.checkData")
    @ResponseBody
    public JsonResult checkData(HttpServletRequest request, Integer taskId) {
        JsonResult jsonResult = JsonResult.success();
        try {
            CpTaskSetup cpTaskSetup = cpTaskSetupService.queryById(taskId);
            List<CpTemplateItem> cpTemplateItemList = cpTemplateItemService.selectCpTemplateItem(cpTaskSetup.getTplId());
            List<CpTaskData> cpTaskData = cpTaskDataService.selectCpTaskData(taskId);

            if(cpTemplateItemList.size()>0 && cpTaskData.size()>0){
                List list = new ArrayList();
                Map map = new HashMap();
                map.put("headList",cpTemplateItemList);
                map.put("personList",cpTaskData);
                jsonResult.setData(map);
            }

        } catch (Exception e) {
            jsonResult = JsonResult.failMessage("获取数据失败");
            e.printStackTrace();
        }
        return jsonResult;
    }

    @PostMapping("/excel/import.do")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return JsonResult.fail();
        }

        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }

    @PostMapping("/getCpTaskRule.json")
    @ResponseBody
    public JsonResult getCpTaskRule(Integer taskId) throws Exception {
       List<CpTaskRule> rules = cpTaskSetupService.selectCpTaskRule(taskId);
        return JsonResult.success(rules);
    }




}
